package com.gourd.common.handler;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.gourd.common.rbac.vo.JwtUser;
import com.gourd.common.utils.JwtUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自定义填充公共字段 ,即没有传的字段自动填充
 *
 * @author gourd
 **/
@Component
public class MyMetaObjectHandler extends MetaObjectHandler  {
    /**
     *  新增填充
     *
     *  @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createdBy = metaObject.getValue("createdBy");
        Object createdTime = metaObject.getValue("createdTime");
        Object version = metaObject.getValue("version");
        Object deleted = metaObject.getValue("deleted");
        //获取当前登录用户
        JwtUser userInfo = JwtUtil.getUserInfo();
        if(userInfo != null){
            if (null == createdBy) {
                metaObject.setValue("createdBy", userInfo.getId());
            }
            if (null == createdTime) {
                metaObject.setValue("createdTime", new Date());
            }
            if (null == version) {
                metaObject.setValue("version", 1L);
            }
            if (null == deleted) {
                metaObject.setValue("deleted", false);
            }
        }

    }

    /**
     * 更新填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Object updatedBy = metaObject.getValue("updatedBy");
        Object updatedTime = metaObject.getValue("updatedTime");
        //获取当前登录用户
        JwtUser userInfo = JwtUtil.getUserInfo();
        if(userInfo != null){
            if (null == updatedBy) {
                metaObject.setValue("updatedBy", userInfo.getId());
            }
            if (null == updatedTime) {
                metaObject.setValue("updatedTime", new Date());
            }
        }

    }
}